# coding=utf-8
import json
import urllib
from urllib import parse
import logging

from django.http import Http404
from rest_framework.exceptions import AuthenticationFailed

server_logger = logging.getLogger("server")
import chardet
import requests

from urllib.parse import urlencode, quote, unquote

'''
maokoulingClass.py 说明
            class maokouling_ONE():  我的猫口令配置信息
            |
            #根据id获得商品的高佣长链接
            def tblink_get_gaoyong(config):
            |
'''


# 每个人配置一个请求信息，要求账户设置白名单
# pid（mm_账号id_推广渠道id_推广位id）
# mm_memberId_siteId_adzoneId
# mm_28964573_303450418_82851750421
# 每个人配置一个请求信息，要求账户设置白名单

class maokouling_Accunt():
    def __init__(self, apkey='6e39417a-bc77-3d4d-c2ae-0a51f37d2574', key_id='J4765683946244691'):
        self.jdid = '100008829953'
        self.apkey = apkey
        self.key_id = key_id
        self.realItemUrl_shot = ''
        self.realItemUrl_long = ''
        self.realShopUrl = ''

    def getLongUrl_By_FakeUrl(self, FakeUrl):
        # 传入别人的淘客链接，进行转链，换取自己的长连接和短链接
        # 验证是否是unicode编码，如果编码网址错了，就换成另一种
        try:
            url = f'''http://api.web.ecapi.cn/jingdong/doItemCpsUrl?apkey={self.apkey}&materialId={quote(FakeUrl)}&key_id={self.key_id}&chainType=3'''
            itemJson = requests.get(url, timeout=100)
            if itemJson.json()['code'] != 200:
                raise Exception
        except:
            url = f'''http://api.web.ecapi.cn/jingdong/doItemCpsUrl?apkey={self.apkey}&materialId={FakeUrl}&key_id={self.key_id}&chainType=3'''
            itemJson = requests.get(url, timeout=100)
        print(itemJson.json())

        self.realItemUrl_shot = itemJson.json()['data']['shortURL']
        self.realItemUrl_long = itemJson.json()['data']['clickURL']
        del itemJson
        return self.realItemUrl_shot, self.realItemUrl_long

    def getjdid(self, shotUrl):

        # 通过短链接获取商品具体信息，包括id，商品名，价格等内容
        url = f'''http://api.web.ecapi.cn/jingdong/getJdUnionItems?apkey={self.apkey}&keyword={quote(shotUrl)}'''
        # print(url)
        itemJson = requests.get(url, timeout=100)
        server_logger.error(itemJson.json())
        # print(int(itemJson.json()['data']['totalCount']))
        try:
            jdid = int(itemJson.json()['data']['list'][0]['materialUrl'].replace('item.jd.com/', '').replace('.html', ''))
            shopid = itemJson.json()['data']['list'][0]['shopInfo']['shopId']
            shopname = itemJson.json()['data']['list'][0]['shopInfo']['shopName']
            skuName = itemJson.json()['data']['list'][0]['skuName']
            item_MainImg = itemJson.json()['data']['list'][0]['imageInfo']['imageList'][0]['url']
            item_price = itemJson.json()['data']['list'][0]['priceInfo']['price']
            print('店铺id', jdid, '店铺名称', shopid, '商品id', shopname)
            del itemJson
            return jdid, shopid, shopname, skuName, item_MainImg,item_price
        except Exception as e:
            server_logger.error(f"京东商品查询API，函数名：getjdid，例外信息：开始通过长链接换取id，调用函数 maokouling_Accunt 文件中getjdid  [京东商品查询API]")
            # logging.error(f"京东商品查询API，：{url} ，返回值：{itemJson.json()}，函数名：getjdid，例外信息：开始通过长链接换取id，调用函数 maokouling_Accunt 文件中getjdid  [京东商品查询API]")
            return [], [], [], [], [],[]


if __name__ == '__main__':
    # abc = maokouling_ONE()
    #
    # abc.itemid = 45074712601
    #
    # abc.userid = item_to_SELLID(abc)
    # # print(tblink_get_gaoyong(abc))
    # abc.itemTbkLink = tblink_get_gaoyong(abc)
    # print(tblink_get_gaoyong(abc))
    # print(userid_to_shopTBK_link(abc))

    # 喵口令通过别人分享的url获取京东itemid,shopid,shopname
    myAccunt = maokouling_Accunt()
    shotUrl, longUrl = myAccunt.getLongUrl_By_FakeUrl(
        'https://union-click.jd.com/jdc?e=&p=AyIGZRhfHAUVDlIYUxwyEgZUGFsWAhUHUB1YHAsiQwpDBUoyS0IQWhkeHAxfEE8HCl4NXAAECUteDEEFWA8LRUpTEwQLR0dKWQoVHUVBRn8AF1sUAxEHVhtcFQcUBFwSa2t%2BVwEpEgNQYGdXE2s4R0pTXx5hXnUOHjdUK1sUAxIBVBxSFwAiN1Uca1RsEgZVGVkcABU3VCtbEgITBFIZUh0BEwJRK1wVCyJcAHUuQ0l5Rg9iL3VfZXFlK2sWMiI3VStYJUB8U1wcX0BQRwQFE1sVBxBSVhNaFgEXB1AdXh0KQQBSGF8lABMGURI%3D')
    print(shotUrl)
    jdid, shopid, shopname, skuName, item_MainImg,item_price = myAccunt.getjdid(shotUrl)


